<?php
class Game_Of_Life_Engine {
    public $w;
    public $h;
    public $board;
    public $display;
    public function __construct($w, $h,$display) {
        $this->display = $display;
        $this->w = $w;
        $this->h = $h;
        $this->buildBoard();
    }
    private function buildBoard() {
        for ($x = 0;$x<$this->w;$x++) {
            for ($y = 0;$y<$this->h;$y++) {        
                $this->board[$x][$y] = false;               
            }
        }
    }
    public function turn() {        
        for ($x = 0;$x<$this->w;$x++) {
            for ($y = 0;$y<$this->h;$y++) {
                $nc = $this->getNeighborCount($x, $y);
                if ($this->board[$x][$y]) {
                    if ($nc>1 && $nc<4) {
                        $this->boardt[$x][$y] = true;
                    } else {
                        $this->boardt[$x][$y] = false;
                    }
                } else {
                    if ($nc == 3) {
                        $this->boardt[$x][$y] = true;
                    } else {
                        $this->boardt[$x][$y] = false;
                    }
                }
                if ($this->boardt[$x][$y] != $this->board[$x][$y]) {
                    if (!$this->display->q) {
                        $this->display->setPix($this->display->W['board'], $x*$this->display->ENV['pSize'], $y*$this->display->ENV['pSize'], $this->boardt[$x][$y]);
                    }
                }
            }
        }
        $this->board = $this->boardt;
    }
    private function getNeighborCount($x, $y) {
        $c = 0;
        $upx = $x;
        $upy = ($y>0) ? $y-1 : $this->h-1;
        $downx = $x;
        $downy = ($y<$this->h-1) ? $y+1 : 0;
        $leftx = ($x>0) ? $x-1 : $this->w-1;
        $lefty = $y;
        $rightx = ($x<$this->w-1) ? $x+1 : 0;
        $righty = $y;
        if ($this->board[$upx][$upy]) {$c++;}
        if ($this->board[$downx][$downy]) {$c++;}
        if ($this->board[$leftx][$lefty]) {$c++;}
        if ($this->board[$rightx][$righty]) {$c++;}
        if ($this->board[$leftx][$upy]) {$c++;}
        if ($this->board[$rightx][$upy]) {$c++;}
        if ($this->board[$leftx][$downy]) {$c++;}
        if ($this->board[$rightx][$downy]) {$c++;}
        return $c;
    }
}
?>